<?php 

namespace comments\controller;

require_once("comments/view/CommentView.php");
require_once("comments/model/CommentDAL.php");
require_once("login/model/LoginModel.php");
require_once("common/model/UserDAL.php");

class CommentController {

	/**
	 * @var \comments\view\CommentView $view
	 */
	private $view;
	/**
	 * @var \login\model\LoginModel $loginModel
	 */
	private $loginModel;
	/**
	 * @var \comments\model\CommentDAL $commentDAL
	 */
	private $commentDAL;
	/**
	 * @var \common\model\UserDAL $userDAL
	 */
	private $userDAL;
	
	public function __construct(\comments\view\CommentView $view, \common\model\BaseDAL $baseDAL) {
		$this->view = $view;
		$this->userDAL = new \common\model\UserDAL($baseDAL);
		$this->loginModel = new \login\model\LoginModel($baseDAL);
		$this->commentDAL = new \comments\model\CommentDAL($baseDAL);
	}

	private function updateComment() {
		//get the current user
		$currentUser = $this->loginModel->getSessionUser();
		//match the user with a database user
		$dbUser = $this->userDAL->getUser($currentUser);
		//get the posted comment data from the view
		$comment = $this->view->getCommentData($dbUser);				
		try {
			//add the comment to the database
			$this->commentDAL->updateComment($comment);
		} catch (\Exception $e) {
			
		}	
	}

	private function deleteComment() {
		//get the current user
		$currentUser = $this->loginModel->getSessionUser();
		//match the user with a database user
		$dbUser = $this->userDAL->getUser($currentUser);
		//get the posted comment data from the view
		$comment = $this->view->getCommentData($dbUser);				
		try {
			//add the comment to the database
			$this->commentDAL->deleteComment($comment);
		} catch (\Exception $e) {
			
		}	
	}

	private function addComment() {
		//get the current user
		$currentUser = $this->loginModel->getSessionUser();
		//match the user with a database user
		$dbUser = $this->userDAL->getUser($currentUser);
		//get the posted comment data from the view
		$comment = $this->view->getCommentData($dbUser);				
		try {
			//add the comment to the database
			$this->commentDAL->addComment($comment);
		} catch (\Exception $e) {
			
		}
	}

	/**
	 * @return void
	 */
	public function runComments() {
		//if the user is commenting
		if ($this->view->userCommenting()) {
			$this->addComment();
		}
		else if ($this->view->userUpdatingComment()) {
			$this->updateComment();
		}
		else if ($this->view->userDeletingComment()) {
			$this->deleteComment();
		}
	}
}